<template>
  <!--物资管理-仓库管理-表单列表-分配人员弹窗-表单-->
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="disabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-form-model-item label="" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="list"
            style="margin-bottom: 10px;margin-left: 0px;font-weight: 600; width: 114%;">
            <div style="display: flex;flex-direction: column;">
              <div style="display: flex;align-items: center;">
                <a-button type="primary" @click="handleAddCom" icon="plus"
                  style="width: 150px;text-align: center;margin-bottom: 10px;margin-right: 10px;margin-left: 5px;">新增人员</a-button>
                <a-button type="danger" @click="handleDelCom" v-if="(selectedRowKeys && selectedRowKeys.length>0)"
                  style="width: 100px;text-align: center;margin-bottom: 10px;">批量删除</a-button>
              </div>
              <a-table :columns="columns" :dataSource="model.list" :pagination="false"
                :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                style="margin-bottom: 20px;">
                <template v-for="(col, i) in ['projectName', 'departName', 'userName']" :slot="col"
                  slot-scope="text, record, index">
                  <a-select v-if="col === 'projectName'" :key="col" :disabled="disabled" placeholder="请选择项目"
                    :value="record.projectName" @change="handleChange('project',index,$event)">
                    <a-select-option v-for="(ite,ind) in levelOneOptions" :key="ind" :value="ite">
                      {{ite.label}}
                    </a-select-option>
                  </a-select>
                  <a-select v-if="col === 'departName'" :key="col" :disabled="disabled || record.projectId === ''"
                    placeholder="请选择部门" :value="record.departName" @change="handleChange('depart',index,$event)">
                    <a-select-option v-for="(ite,inde) in record.levelTwoOptions" :key="ind" :value="ite">
                      {{ite.label}}
                    </a-select-option>
                  </a-select>
                  <a-select v-if="col === 'userName'" :key="col" :disabled="disabled || record.departId === ''"
                    placeholder="请选择用户" :value="record.userName" @change="handleChange('user',index,$event)">
                    <a-select-option v-for="(ite,ind) in record.levelThreeOptions" :key="ind" :value="ite">
                      {{ite.label}}
                    </a-select-option>
                  </a-select>
                </template>
              </a-table>
            </div>
          </a-form-model-item>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
  import {
    httpAction,
    getAction
  } from '@/api/manage'
  import {
    validateDuplicateValue
  } from '@/utils/util'
  export default {
    name: 'WtWarehouseForm',
    components: {},
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false,
      },
    },
    data() {
      return {
        model: {
          warehouseId: '',
          list: [],
        },
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 5
          },
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 16
          },
        },
        labelCol2: {
          xs: {
            span: 24
          },
          sm: {
            span: 3
          },
        },
        wrapperCol2: {
          xs: {
            span: 24
          },
          sm: {
            span: 21
          },
        },
        confirmLoading: false,
        levelOneOptions: [], //项目列表
        validatorRules: {},
        columns: [{
            title: '项目',
            dataIndex: 'projectName',
            key: 'projectName',
            align: "center",
            width: '34%',
            scopedSlots: {
              customRender: 'projectName'
            }
          },
          {
            title: '部门',
            dataIndex: 'departName',
            key: 'departName',
            align: "center",
            width: '33%',
            scopedSlots: {
              customRender: 'departName'
            }
          },
          {
            title: '人员',
            dataIndex: 'userName',
            key: 'userName',
            align: "center",
            width: '33%',
            scopedSlots: {
              customRender: 'userName'
            }
          }
        ],
        selectedRowKeys: [],
        url: {
          list: '/materials/wtWarehouseUser/queryByWarehouseId',
          add: '/materials/wtWarehouse/add',
          edit: '/materials/wtWarehouseUser/edit',
          queryById: '/materials/wtWarehouse/queryById',
        },
      }
    },
    created() {

    },
    methods: {
      //表格数据批量删除
      handleDelCom() {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        } else {
          var _self = this;
          this.$confirm({
            title: "确认删除",
            content: "是否删除选中数据?",
            onOk: function() {
              let list = JSON.parse(JSON.stringify(_self.model.list));
              list.forEach((item, index) => {
                _self.$set(item, 'is_sel', false)
                _self.selectedRowKeys.forEach((v, i) => {
                  if (item.key === v) {
                    item.is_sel = true
                  }
                })
              })
              let lists = []
              list.forEach(ite => {
                if (!ite.is_sel) {
                  lists.push(ite)
                }
              })
              _self.selectedRowKeys = [];
              _self.model.list = lists;
            }
          });
        }
      },
      //表格增加数据
      handleAddCom() {
        let ind = (new Date()).getTime();
        this.model.list.push({
          key: ind,
          warehouseId: this.model.warehouseId,
          projectName: '',
          projectId: '',
          departName: '',
          departId: '',
          userName: '',
          userId: '',
          levelTwoOptions: [],
          levelThreeOptions: [],
          editable: true,
          isNew: true
        });
        this.$forceUpdate();
      },
      //下拉选择
      handleChange(type, index, item) {
        console.log(1, type, index, item);
        let _self = this;
        if (type === 'project') {
          this.model.list[index].projectName = item.label;
          this.model.list[index].projectId = item.value;
          //清空联动数据
          this.model.list[index].departName = '';
          this.model.list[index].departId = '';
          this.model.list[index].approverName = '';
          this.model.list[index].approver = '';
          getAction(`/sys/sysDepart/getDepartListByParentId?parentId=${this.model.list[index].projectId}`).then((
            res) => {
            if (res.success) {
              _self.model.list[index].levelTwoOptions = [];
              let treeList = res.result;
              _self.$nextTick(() => {
                _self.model.list[index].levelTwoOptions = [...treeList].map((v) => ({
                  ...v,
                  value: v.id,
                  label: v.departName,
                }))
                _self.$forceUpdate();
              })
            }
          })
        } else if (type === 'depart') {
          this.model.list[index].departName = item.label;
          this.model.list[index].departId = item.value;
          //清空联动数据
          this.model.list[index].approverName = '';
          this.model.list[index].approver = '';
          getAction(`/sys/sysDepart/getUsersByDepartId?id=${this.model.list[index].departId}`).then((res) => {
            if (res.success) {
              _self.model.list[index].levelThreeOptions = [];
              let treeList = res.result;
              _self.$nextTick(() => {
                _self.model.list[index].levelThreeOptions = [...treeList].map((v) => ({
                  ...v,
                  value: v.id,
                  label: v.realname,
                }))
                _self.$forceUpdate();
              })
            }
          })
        } else if (type === 'user') {
          this.model.list[index].userName = item.label;
          this.model.list[index].userId = item.value;
        }
      },
      //选中表格
      onSelectChange(selectedRowKeys) {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.selectedRowKeys = selectedRowKeys;
      },
      add() {
        this.edit(this.modelDefault)
      },
      edit(record) {
        console.log(11, record)
        this.model.warehouseId = record.id;
        this.visible = true;
        this.loadTree(record);
      },
      loadTree(record) {
        getAction(`/sys/sysDepart/getDepartByOrgType?orgType=1`).then((res) => {
          if (res.success) {
            let treeList = res.result
            this.levelOneOptions = [...treeList].map((v) => ({
              ...v,
              value: v.id,
              label: v.departName,
            }))
            getAction(`/materials/wtWarehouseUser/queryByWarehouseId?warehouseId=${record.id}`).then((res1) => {
              if (res1.success) {
                let treeList = res1.result;
                if (treeList && treeList.length > 0) {
                  this.model.list = [...treeList].map((v) => ({
                    ...v,
                    key: v.id,
                    projectName: v.projdectName,
                    projectId: v.projectId,
                    levelTwoOptions: [],
                    levelThreeOptions: [],
                    editable: true,
                    isNew: true
                  }))
                  this.$forceUpdate();
                }
              }
            })
          }
        })
      },
      submitForm() {
        const _self = this
        // 触发表单验证
        this.$refs.form.validate((valid) => {
          if (valid) {
            _self.confirmLoading = true;
            let httpurl = '';
            let method = '';
            let params = {};
            if (!!this.model.warehouseId) {
              httpurl += this.url.edit;
              method = 'post';
              params = this.model;
            }
            httpAction(httpurl, params, 'POST').then((res) => {
                if (res.success) {
                  _self.$message.success(res.message)
                  _self.$emit('ok')
                } else {
                  _self.$message.warning(res.message)
                }
              })
              .finally(() => {
                _self.confirmLoading = false
              })
          }
        })
      },
    },
  }
</script>